#include "networkhttprequest.h"
#include "networkresponse.h"
#include "networkmanager.h"

#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>


using namespace Network;
HttpRequest::HttpRequest() :
    m_reply(NULL)
{
}


bool HttpRequest::post(Manager *manager)
{
    if (m_reply != NULL)
        return false;

    m_reply = post(manager->manager(), url());
    if (m_reply == NULL)
        return false;

    m_connection = connect(m_reply, &QNetworkReply::finished, this, &Network::HttpRequest::replied);
    moveToThread(manager->worker());
    if (m_connection == NULL) {
        m_reply->abort();
        m_reply = NULL;
        return false;
    }

    return true;
}

void HttpRequest::replied()
{
    if (m_reply == NULL)
        return;

    Response &response = this->response();
    response.parse(*m_reply);
    emit responded(this);

}

void HttpRequest::abort()
{
    if (m_reply == NULL)
        return;

    m_reply->abort();
}
